package com.eltonkent.dashboard.service.requesthandler;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import com.eltonkent.dashboard.constants.ApplicationConstants;
import com.eltonkent.dashboard.data.container.Container;
import com.eltonkent.dashboard.data.container.WeatherContainer;
import com.eltonkent.dashboard.service.helper.HttpServiceHelper;
import com.eltonkent.dashboard.service.responsehandler.GoogleWeatherHandler;
import com.eltonkent.dashboard.util.gps.WebResponseNotificationListener;
import com.eltonkent.dashboard.util.logger.Logger;

public class GoogleWeatherRequest extends HttpRequest {

	private final String address;

	public GoogleWeatherRequest(WebResponseNotificationListener listener,
			String address) {
		super(listener);
		this.address = address;
	}

	@Override
	public Container call() throws Exception {
		Logger.i("DBA","Google Weather response received");
		HttpEntity httpEntity = httpServiceHelper.execute();
		InputStream is = httpEntity.getContent();
		GoogleWeatherHandler xmlHandler = new GoogleWeatherHandler();
		WeatherContainer container = xmlHandler.deserialize(is);
		Logger.d("DBA","[Google Weather Response [call()]]"+container.toString());
		return container;
	}

	@Override
	public void postExecute(Container t, Throwable throwable) {
		if(throwable!=null){
			Logger.e("DBA","Exception"+throwable.getMessage());
		}
		if (t != null) {
			WeatherContainer container = (WeatherContainer) t;
			Logger.d("DBA","[Google Weather Response postExecute()]"+container.toString());
			if (container.isValidResponse()) {
				listener.notifyWeather(container);
			}
		}
	}

	@Override
	public void preExecute() throws Exception {
		Log.i("DBA", "preExecute");
		httpServiceHelper = new HttpServiceHelper(new URI(
				ApplicationConstants.URL_GOOGLE_WEATHER));
		List<NameValuePair> requestParameter = new ArrayList<NameValuePair>();
		NameValuePair param = new BasicNameValuePair("weather", address);
		requestParameter.add(param);
		param = new BasicNameValuePair("key",
				ApplicationConstants.API_KEY_GOOGLE);
		requestParameter.add(param);
		httpServiceHelper.setRequestParameter(requestParameter);
	}

}
